﻿Imports System.Threading
Imports HslCommunication
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class FormPlanMes
    Public usr As String
    Dim objPgdMes As New clsPgdMes
    Dim objWorkshopCurrent As New clsWorkshopCurrent
    Dim objSysParam As New clsSysParam
    Dim httpHelper As New HttpHelper
    Dim txt As TextBox
    Dim current_section As String '当前工序
    Dim ping = New Net.NetworkInformation.Ping()
    Private Sub FormPlanMes_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        current_section = GetIniFile("SECTION", "current_section", "", g_szInitFileName)
        Dim startDate As String = Date.Now.ToShortDateString()
        txtStartDate.Text = startDate
        Dim endDate As String = Date.Now.ToShortDateString()
        txtEndDate.Text = endDate
        setDgvData()
    End Sub

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        setDgvData()
    End Sub

    Private Sub setDgvData()
        If String.IsNullOrEmpty(txtStartDate.Text.Trim()) = False And String.IsNullOrEmpty(txtEndDate.Text.Trim()) = False Then
            Dim dt As DataTable = objPgdMes.getYzzPgd(0, txtStartDate.Text, txtEndDate.Text, chkFinishCount.Checked)
            If dt.Rows.Count > 0 Then
                dt.Columns.Add("validity_name")
                For Each row As DataRow In dt.Rows
                    If row("validity") = "0" Then
                        row("validity_name") = "无效"
                    Else
                        row("validity_name") = "有效"
                    End If
                Next
            End If
            dgv.AutoGenerateColumns = False
            dgv.DataSource = dt
        Else
            MsgBox("请选择开始时间和结束时间", MsgBoxStyle.Information, "提示")
        End If
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        If dgv.SelectedRows.Count > 0 Then
            Dim s_m As String = dgv.SelectedRows(0).Cells("support_model").Value.ToString()
            Dim o_c As String = dgv.SelectedRows(0).Cells("ColOperCount").Value.ToString()
            Dim f_c As String = dgv.SelectedRows(0).Cells("Col_finish_count").Value.ToString()
            Dim rtn As Integer = objWorkshopCurrent.SaveData(dgv.SelectedRows(0).Cells("sys_id").Value.ToString(),
                                                              s_m, "0", current_section, o_c, f_c)
            If rtn = -2 Then
                MsgBox(btnSave.Text + "失败")
            Else
                MsgBox(btnSave.Text + "成功")
                If current_section.Equals("YZZ") Then
                    setOneParamers(o_c, f_c, s_m)
                End If
                CType(Owner, FormMain).initForm()
            End If
        Else
            MsgBox("请选择需设定的生产计划")
        End If
    End Sub

    ''' <summary>
    ''' 对接驳工位1车间法兰板、骨架板2、3的计划数
    ''' </summary>
    Private Sub setOneParamers(plan_count As String, finish_count As String, support_model As String)
        Dim _1F_PLC As SiemensS7Net
        Dim _1G2_PLC As SiemensS7Net
        Dim _1G3_PLC As SiemensS7Net
        '1车间法兰板的计划数
        _1F_PLC = New SiemensS7Net(SiemensPLCS.S1200)
        _1F_PLC.IpAddress = "172.16.20.13"
        _1F_PLC.Port = 102

        '需求数=计划数-完成数
        Dim _NeedCount As Short = CShort(CInt(plan_count) - CInt(finish_count))
        Dim pingResult1F As Net.NetworkInformation.PingReply = ping.Send(_1F_PLC.IpAddress)
        Try
            If pingResult1F.Status = Net.NetworkInformation.IPStatus.Success Then
                If _1F_PLC.ConnectServer().IsSuccess Then
                    '设定
                    Dim objProdSpec As New clsProdSpec
                    Dim dtProdSpec As DataTable = objProdSpec.selectAllbySpecId(support_model)
                    Dim objFLB As New clsFlbMst
                    '根据规格得到当前类型一个料框多少块
                    Dim dtflbMst As DataTable = objFLB.getList(dtProdSpec.Rows(0)("flb_material_code"))
                    If dtflbMst.Rows.Count > 0 Then
                        Dim flbLKcount As Integer = CInt(dtflbMst.Rows(0)("count_down"))
                        '得出需要几个料框
                        Dim flbLK As Integer = Math.Ceiling(_NeedCount / flbLKcount)
                        objSysParam.setSysParam("FLB_need_Count_For_YZZ", flbLK)

                        _1F_PLC.Write("DB1.DBW14", flbLK) '设定MES要求数量
                        _1F_PLC.Write("DB1.DBX1.3", True) '计数清零
                        Thread.Sleep(500)
                        _1F_PLC.Write("DB1.DBX1.3", False) '计数清零
                        _1F_PLC.Write("DB1.DBX1.2", True) '计数开始
                        Thread.Sleep(500)
                        _1F_PLC.Write("DB1.DBX1.2", False) '计数开始
                        _1F_PLC.ConnectClose()
                    End If
                End If
            End If
        Catch ex As Exception

        End Try

        '取得骨架板当前生产规格
        Dim gjbCurDt As DataTable = objWorkshopCurrent.GetListByWorkShopIdAndCurrentSection("1", "GJBZP")
        If gjbCurDt.Rows.Count > 0 Then
            If gjbCurDt.Rows(0)("support_model") = support_model Then '如果1，2车间的物料编码一样

                '骨架板2的计划数
                _1G2_PLC = New SiemensS7Net(SiemensPLCS.S1200)
                _1G2_PLC.IpAddress = "172.16.20.14"
                _1G2_PLC.Port = 102
                Dim pingResult1G2 As Net.NetworkInformation.PingReply = ping.Send(_1G2_PLC.IpAddress)
                Try
                    If pingResult1G2.Status = Net.NetworkInformation.IPStatus.Success Then
                        If _1G2_PLC.ConnectServer().IsSuccess Then
                            _1G2_PLC.Write("DB15.DBW12", _NeedCount) '设定MES要求数量
                            _1F_PLC.Write("DB15.DBX20.0", True) '计数开始
                            Thread.Sleep(500)
                            _1F_PLC.Write("DB15.DBX20.0", False) '计数开始
                            _1F_PLC.Write("DB15.DBX20.1", True) '计数清零
                            Thread.Sleep(500)
                            _1F_PLC.Write("DB15.DBX20.1", False) '计数清零
                            _1G2_PLC.ConnectClose()
                            objSysParam.setSysParam("GJB_need_Count_For_YZZ", _NeedCount.ToString)
                        End If
                    End If
                Catch ex As Exception

                End Try
                Exit Sub
            End If
        End If

        '骨架板3的计划数
        _1G3_PLC = New SiemensS7Net(SiemensPLCS.S1200)
        _1G3_PLC.IpAddress = "172.16.20.18"
        _1G3_PLC.Port = 102
        Dim pingResult1G3 As Net.NetworkInformation.PingReply = ping.Send(_1G3_PLC.IpAddress)
        Try
            If pingResult1G3.Status = Net.NetworkInformation.IPStatus.Success Then
                If _1G3_PLC.ConnectServer().IsSuccess Then
                    _1G3_PLC.Write("DB1.DBW14", _NeedCount) '设定MES要求数量
                    _1G3_PLC.Write("DB1.DBX1.3", True) '计数清零
                    Thread.Sleep(500)
                    _1G3_PLC.Write("DB1.DBX1.3", False) '计数清零
                    _1G3_PLC.Write("DB1.DBX1.2", True) '计数开始
                    Thread.Sleep(500)
                    _1G3_PLC.Write("DB1.DBX1.2", False) '计数开始
                    _1G3_PLC.ConnectClose()
                    objSysParam.setSysParam("GJB_need_Count_For_YZZ", _NeedCount.ToString)
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnMesPlan_Click(sender As Object, e As EventArgs) Handles btnMesPlan.Click
        If String.IsNullOrEmpty(txtStartDate.Text.Trim()) = False And String.IsNullOrEmpty(txtEndDate.Text.Trim()) = False Then
            'Dim params As String = "{""workshop"":""预组装"",""date"":""" & "2021-12-08" & """,""compid"":""0de02b54-4e55-4dbf-ab89-f785df5f405c""}"
            Dim params As String = "{""workshop"":""预组装"",""startdate"":""" & DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd") & """,""enddate"":""" & DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd") & """,""compid"":""0de02b54-4e55-4dbf-ab89-f785df5f405c""}"
            Dim rtn As String = httpHelper.HttpPostWebService("findDispatchOrderInfoListByTimeAndCJ", params)
            'MsgBox(rtn)
            Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
            Dim code As String = jo("code").ToString() '输出0
            'MsgBox(code)
            Dim data As String = jo("data").ToString() '输出0
            'data = "[{""dispatchingorder"":""PGDH211103001"",
            '""start_time"":""2021-11-02 00:00:00"",
            '""end_time"":""2021-11-02 23:59:59"",
            '""project_code"":""fgm-test-0001"",
            '""project_name"":""fgm-test-0001"",
            '""equip_id"":""070046,070023,070020,070011,"",
            '""jp_type"":""mes不存在"",
            '""prod_spec_id"":""HDR-0.4-201-035-18"",""count"":9.0},
            '{""dispatchingorder"":""PGDH211103222"",""start_time"":""2021-11-02 00:00:00"",
            '""end_time"":""2021-11-02 23:59:59"",
            '""project_code"":""fgm-test-0001"",
            '""project_name"":""fgm-test-0001"",
            '""equip_id"":""070046,070023,070020,070011,"",
            '""jp_type"":""mes不存在"",
            '""prod_spec_id"":""HDR-0.4-201-035-18"",""count"":9.0}]"
            'MsgBox(data)
            Dim jarray As JArray = JArray.Parse(data)
            If jarray.Count > 0 Then
                For index = 0 To jarray.Count - 1
                    Dim en As New entityPgdMes
                    en.pgd_code = jarray(index)("dispatchingorder")
                    en.oper_date = DateTime.Parse(jarray(index)("start_time")).ToShortDateString()
                    en.start_time = jarray(index)("start_time").ToString()
                    en.end_time = DateTime.Parse(jarray(index)("start_time")).AddDays(1).ToString()
                    en.support_model = jarray(index)("p_prod_spec_id")
                    en.type_value = jarray(index)("prod_spec_id")
                    en.mes_project_code = jarray(index)("project_code")
                    en.mes_project_name = jarray(index)("project_name")
                    en.oper_count = jarray(index)("count")
                    en.oper_count_all = jarray(index)("number")
                    en.workshop_id = 0
                    en.validity = "1"
                    en.status = "1"
                    en.origin = "0"
                    en.Ope = usr
                    en.jp_type = jarray(index)("jp_code")
                    en.note = String.Empty
                    Dim dtmesdata As DataTable = objPgdMes.getListByPgd(jarray(index)("dispatchingorder").ToString())
                    If dtmesdata.Rows.Count = 0 Then
                        Dim rtn_save As Integer = objPgdMes.insertxjORyzz(en)
                    Else
                        Dim rtn_save As Integer = objPgdMes.updatexjORyzz(en)
                    End If
                Next
            Else
                MsgBox("没有数据", MsgBoxStyle.Information, "提示")
            End If
        Else
            MsgBox("请选择开始时间和结束时间", MsgBoxStyle.Information, "提示")
        End If
    End Sub

    Private Sub txt_MouseClick(sender As Object, e As MouseEventArgs) Handles txtStartDate.MouseClick, txtEndDate.MouseClick
        txt = CType(sender, TextBox)
        DateNavigator1.Left = txt.Left
        DateNavigator1.Top = txt.Location.Y + txt.Height
        DateNavigator1.Visible = True
    End Sub


    Private Sub DateNavigator1_DateTimeChanged(sender As Object, e As EventArgs) Handles DateNavigator1.DateTimeChanged
        txt.Text = DateNavigator1.DateTime.ToShortDateString()
        DateNavigator1.Visible = False
    End Sub

End Class

Public Class entityPgdMes
    Public pgd_code As String
    Public oper_date As String
    Public mes_project_code As String
    Public mes_project_name As String
    Public support_model As String
    Public type_value As String
    Public oper_count As String
    Public oper_count_all As String
    Public lhj As String
    Public lhj_type As String
    Public note As String
    Public workshop_id As Integer
    Public validity As String
    Public status As String
    Public origin As String
    Public Ope As String
    Public start_time As String
    Public end_time As String
    Public jp_type As String
    Public jp_spec As String

End Class